<template>
    <MyCard>
        <div class="top-container">
            <div class="title">
                <div></div>
                角色管理
            </div>
            <el-button type="primary" style="width: 60px; height: 40px;" @click="updateRole">
                保存
            </el-button>
        </div>

        <div class="form-container">

            <div class="form-container-left">
                <el-table :data="roleData" style="width: 100%"
                    :header-cell-style="{ fontWeight: 'normal', color: '#515a6e', }" row-key="_id" show-overflow-tooltip
                    :stripe="false" @header-click="handleHeaderClick" @row-click="getPermissionData">
                    <el-table-column prop="name" label="角色" width="150" />
                    <el-table-column label="+新增角色" width="150">
                        <template #header>
                            <div style="color: #0256FF;">+新增角色</div>
                        </template>
                        <template #default="scope">
                            <div class="hover-icon">
                                <el-icon>
                                    <EditPen color="#0256FF" @click="onAddRoleBtn.openDialog(scope.row)" />
                                </el-icon>
                                <el-icon @click=" onDeleteBtn(scope.row._id)">
                                    <Delete color="red" />
                                </el-icon>
                            </div>
                        </template>

                    </el-table-column>
                </el-table>
            </div>


            <div class="form-container-right">

                <el-form :model="formItem" label-width="120">
                    <el-form-item label="管理角色权限: ">
                        <div>{{ choseName }}</div>
                        <div style="display: flex;align-items: start; width:100%; ">
                            <div style="flex-grow: 1; height: 503px; overflow-y: scroll" custom-tree-node-container>
                                <el-tree ref="treeRef" show-checkbox :data="permissionsData" node-key="_id"
                                    :props="{ label: 'title' }" :check-strictly="true" @check="handleCheckChange" />

                            </div>
                        </div>
                    </el-form-item>
                </el-form>
            </div>
        </div>
        <RoleForm @findTag="getData" ref="openDialog"></RoleForm>
    </MyCard>
</template>

<script setup>
import { onMounted, ref, useTemplateRef } from 'vue';
import { deleteRoleApi, findRoleApi, updateRoleApi } from '../../../api/role';
import { EditPen, Delete } from '@element-plus/icons-vue'
import { findPermissionsApi } from '../../../api/permissions';
import RoleForm from './roleForm.vue';
import MyCard from '../../../components/MyCard.vue';
const columns = ref([
    { label: '角色', prop: 'name' },
    { label: '+新增角色', prop: '_id' },
])
const roleData = ref([]);
const formItem = ref({});
const treeRef = ref();
const choseName = ref('请选择操作对象');
const changeItem = ref({});
const onAddRoleBtn = useTemplateRef('openDialog');
const permissionsData = ref([]);

onMounted(() => {
    getData();
    findPermissions();
})


function handleHeaderClick(column) {
    if (column.label == "+新增角色") {
        onAddRoleBtn.value.openDialog();
    }
};

function addBtn(data) {
    // if (data.row == 1 && data.column == 2) {
    return {
        color: "red",
        backgroundColor: 'red'
    }
    // }

}




//删除role
function onDeleteBtn(_id) {
    ElMessageBox.confirm(
        '删除后无法恢复，定要删除此条记录吗？',
        '确认删除',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            deleteRoleApi({
                _id,
            })
                .then((res) => {
                    if (res.code == 200) {
                        ElMessage.success('删除成功!');
                        getData();
                    } else {
                        ElMessage.error(res.message);
                    }
                })
        })
        .catch(() => { })
}

function getData() {
    findRoleApi(
        // {group:}待传
    ).then(res => {
        if (res.code == 200) {
            roleData.value = res.data.rows
        }
    })
}
function findPermissions() {
    findPermissionsApi().then(res => {
        if (res.code == 200) {
            permissionsData.value = res.data.rows;
        }
    })
}
function getPermissionData(data) {
    changeItem.value = data
    choseName.value = data.name;
    const temp = (data.permissions).map(item => item._id);
    treeRef.value.setCheckedKeys(temp, false)

}


function updateRole() {
    updateRoleApi({ ...changeItem.value, permissions: treeRef.value.getCheckedKeys(false) }).then(res => {
        if (res.code == 200) {
            ElMessage.success('修改成功!');
            getData();
        } else {
            ElMessage.error(res.message);
        }
    })
}




// 当用户点击Tree组件中的复选框时，触发该事件
const handleCheckChange = (node, checkedStatus) => {
    // 判断选中的数组中是否有当前点击的节点
    const checked = checkedStatus.checkedKeys.includes(node._id);
    // 进入if，说明用户当前的操作是【勾选】
    if (checked) {
        // 选中节点时处理子节点和父节点
        if (node.children?.length) {
            // 勾选所有子节点
            checkAllChildren(node, true);
        }
        checkAllParents(node);
    } else {
        // 取消节点时处理子节点
        if (node.children?.length) {
            checkAllChildren(node, false);
        }
    }
}
// 递归操作子节点
const checkAllChildren = (node, checked) => {
    node.children.forEach((child) => {
        treeRef.value?.setChecked(child._id, checked, false);
        if (child.children) checkAllChildren(child, checked);
    });
}
// 递归操作父节点
const checkAllParents = (node) => {
    let parent = getParentNode(node);
    while (parent) {
        treeRef.value?.setChecked(parent._id, true, false);
        parent = getParentNode(parent);
    }
}
// 父节点查找算法，返回目标节点的直接父节点
const getParentNode = (node) => {
    const findParent = (data, targetId, parent) => {
        for (const item of data) {
            if (item._id === targetId) return parent;
            if (item.children) {
                const found = findParent(item.children, targetId, item);
                if (found) return found;
            }
        }
        return null;
    }
    return findParent(permissionsData.value, node._id, null);
}

</script>

<style scoped lang="scss">
.is-penultimate>.el-tree-node__content {
    color: #626aef;
}

.is-penultimate>.el-tree-node__children>div {
    display: inline-block;
    margin-right: 4px;

    &:not(:first-child) .el-tree-node__content {
        padding-left: 0px !important;
    }

    .el-tree-node__content {
        padding-right: 16px;
    }
}




// // 隐藏overflow滚动条
::-webkit-scrollbar {
    display: none;
}

.el-table {
    --el-table-border-color: #ffffff;
}

.top-container {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}

.title {
    display: flex;
    line-height: 1;
    justify-content: center;
    align-items: center;

    div {
        margin-top: -1px;
        width: 6px;
        height: 23px;
        background-color: rgba(41, 132, 248, 1);
        margin-right: 10px;
        border-radius: 60px;
    }

    font-size: 18px;
    color: rgba(51, 51, 51, 0.898039215686275);

}

.form-container {
    display: flex;
    justify-content: space-between;
}

.form-container-left {
    width: 300px;
    height: 600px;
    border-width: 1px;
    border-style: solid;
    border-color: rgba(242, 242, 242, 1);
    border-radius: 4px;
    background-color: #ffffff;
}

.el-table {
    border: 0;
}

.form-container-right {
    width: 755px;
    height: 600px;
    border-width: 1px;
    border-style: solid;
    border-color: rgba(242, 242, 242, 1);
    border-radius: 4px;
}

.hover-icon {
    display: flex;
    justify-content: space-between;
    width: 50px;
}
</style>